<template>
  <a-card>
    <!-- 查询 -->
    <a-form
        ref="searchFormRef"
        :model="search_form"
        @submit="handleSearchSubmit"
        :label-col-props="{ span: 6 }"
        :wrapper-col-props="{ span: 18 }"
        label-align="left"
    >
      <a-row>
        <a-col :flex="1">
          <a-row :gutter="16">
            <a-col :span="8">
              <a-form-item label="申请人" field="userId">
                <!--                <a-input placeholder="请输入申请人ID" v-model="search_form.userId"></a-input>-->
                <a-select v-model="search_form.userId" placeholder="请选择申请人">
                  <a-option v-for="user in users" :key="user.userIdWbxqy" :value="user.userIdWbxqy">
                    {{ user.usernameWbxqy }}
                  </a-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="车辆" field="carId">
                <!--                <a-input placeholder="请输入车辆ID" v-model="search_form.carId"></a-input>-->
                <a-select v-model="search_form.carId" placeholder="请选择车辆">
                  <a-option v-for="car in cars" :key="car.carIdWbxqy" :value="car.carIdWbxqy">
                    {{ car.licensePlateWbxqy }}
                  </a-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="司机" field="driverId">
                <!--                <a-input placeholder="请输入司机ID" v-model="search_form.driverId"></a-input>-->
                <a-select v-model="search_form.driverId" placeholder="请选择司机">
                  <a-option v-for="driver in drivers" :key="driver.userIdWbxqy" :value="driver.userIdWbxqy">
                    {{ driver.usernameWbxqy }}
                  </a-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="申请状态" field="status">
                <a-select placeholder="请选择申请状态" v-model="search_form.status" allow-clear>
                  <a-option value="S">待审批</a-option>
                  <a-option value="A">已批准</a-option>
                  <a-option value="R">已拒绝</a-option>
                  <a-option value="E">行程已结束</a-option>
                </a-select>
              </a-form-item>
            </a-col>
          </a-row>
        </a-col>
        <a-divider style="height: 84px" direction="vertical"/>
        <a-col :flex="'86px'" style="text-align: right">
          <a-space direction="vertical" :size="18">
            <a-button type="primary" html-type="submit">
              <template #icon>
                <icon-search/>
              </template>
              查询
            </a-button>
            <a-button @click="$refs.searchFormRef.resetFields()">
              <template #icon>
                <icon-refresh/>
              </template>
              重置
            </a-button>
          </a-space>
        </a-col>
      </a-row>
    </a-form>
    <!-- 信息展示 -->
    <a-table :columns="columns" :data="requests" :pagination="pagination" @page-change="handlePaginationChange"
             style="height: 70vh">
      <template #user="{record, rowIndex}">
        {{ record.user.usernameWbxqy }}
      </template>
      <template #car="{record, rowIndex}">
        {{ record.car !== null ? record.car.licensePlateWbxqy : "未分配车辆" }}
      </template>
      <template #driver="{record, rowIndex}">
        {{ record.driver !== null ? record.driver.usernameWbxqy : "未分配司机" }}
      </template>
      <template #status="{ record,rowIndex }">
        <a-tag v-if="record.statusWbxqy === 'S'" color="blue">待审批</a-tag>
        <a-tag v-else-if="record.statusWbxqy === 'A'" color="green">已批准</a-tag>
        <a-tag v-else-if="record.statusWbxqy === 'R'" color="red">已拒绝</a-tag>
        <a-tag v-else-if="record.statusWbxqy === 'E'" color="gray">行程已结束</a-tag>
        <a-tag v-else-if="record.statusWbxqy === 'C'" color="gray">用户已评论</a-tag>
        <a-tag v-else-if="record.statusWbxqy === 'B'" color="gray">管理员已编写报表</a-tag>
      </template>
      <template #operations="{ record,rowIndex }">
        <a-space>
          <a-button
              v-if="record.statusWbxqy==='S'"
              type="outline" @click="openShenPi(record)">
            <template #icon>
              <icon-edit/>
            </template>
            查看详情并审批
          </a-button>
          <a-button
              v-if="record.statusWbxqy==='E'"
              type="outline" @click="openBaoBiao(record.requestIdWbxqy)">
            <template #icon>
              <icon-edit/>
            </template>
            编写报表
          </a-button>
          <a-button
              v-if="record.statusWbxqy==='B'"
              type="outline" @click="openBaoBiaoShow(record.requestIdWbxqy)">
            <template #icon>
              <icon-eye/>
            </template>
            查看报表
          </a-button>
        </a-space>
      </template>
    </a-table>
    <!-- 审批用车申请抽屉 -->
    <a-drawer
        :width="340"
        :visible="showShenPiDrawer"
        @ok="shenPiOk"
        @cancel="shenPiCancel"
        ok-text="同意并分配"
        cancel-text="拒绝并说明"
        unmountOnClose
    >
      <template #title>
        审批用车申请
      </template>
      <div>
        <!-- 展示用车申请信息 -->
        <div class="request-info">
          <p>申请人: {{ requestData.user.usernameWbxqy }}</p>
          <p>申请时间: {{ requestData.requestDateWbxqy }}</p>
          <p>开始时间: {{ requestData.startTimeWbxqy }}</p>
          <p>结束时间: {{ requestData.endTimeWbxqy }}</p>
          <p>状态:
            <a-tag v-if="requestData.statusWbxqy === 'S'" color="blue">待审批</a-tag>
            <a-tag v-else-if="requestData.statusWbxqy === 'A'" color="green">已批准</a-tag>
            <a-tag v-else-if="requestData.statusWbxqy === 'R'" color="red">已拒绝</a-tag>
            <a-tag v-else-if="requestData.statusWbxqy === 'E'" color="gray">行程已结束</a-tag>
            <a-tag v-else-if="reportData.statusWbxqy === 'B'" color="gray">管理员已编写报表</a-tag>
          </p>
        </div>

        <!-- 审批和拒绝表单 -->
        <a-form :model="approvalForm" :rules="shenPiRules" ref="approvalFormRef" layout="vertical">
          <a-form-item label="分配司机" field="driverIdWbxqy">
            <a-select v-model="approvalForm.driverIdWbxqy" placeholder="请选择司机">
              <a-option v-for="driver in freeDrivers" :key="driver.userIdWbxqy" :value="driver.userIdWbxqy.toString()">
                {{ driver.usernameWbxqy }}
              </a-option>
            </a-select>
          </a-form-item>
          <a-form-item label="分配车辆" field="carIdWbxqy">
            <a-select v-model="approvalForm.carIdWbxqy" placeholder="请选择车辆">
              <a-option v-for="car in freeCars" :key="car.carIdWbxqy" :value="car.carIdWbxqy.toString()">
                {{ car.licensePlateWbxqy }}
              </a-option>
            </a-select>
          </a-form-item>
          <a-form-item label="拒绝理由" field="rejectResonWbxqy">
            <a-textarea v-model="approvalForm.rejectResonWbxqy" placeholder="请填写拒绝理由"/>
          </a-form-item>
        </a-form>
      </div>
    </a-drawer>
    <!-- 填写报表抽屉   -->
    <a-drawer
        :width="1000"
        :visible="showBaoBiaoDrawer"
        @ok="baoBiaoOk"
        @cancel="baoBiaoCancel"
        unmountOnClose
    >
      <template #title>
        <div>用车详情</div>
      </template>
      <a-descriptions column="12" :bordered="true">
        <a-descriptions-item label="请求ID" span="12">{{ reportData.requestIdWbxqy }}</a-descriptions-item>
        <a-descriptions-item label="用户信息" span="4">
          <p>用户名: {{ reportData.user?.usernameWbxqy }}</p>
          <p>邮箱: {{ reportData.user?.emailWbxqy }}</p>
          <p>电话号码: {{ reportData.user?.phoneNumberWbxqy }}</p>
          <img :src="reportData.user?.avatarUrlWbxqy" alt="用户头像" style="width: 50px; height: 50px;"/>
        </a-descriptions-item>
        <a-descriptions-item label="车辆信息" span="4">
          <p>车牌: {{ reportData.car?.licensePlateWbxqy }}</p>
          <p>品牌: {{ reportData.car?.brandWbxqy }}</p>
          <p>型号: {{ reportData.car?.modelWbxqy }}</p>
          <img :src="reportData.car?.imageUrlWbxqy" alt="车辆图片" style="width: 50px; height: 50px;"/>
        </a-descriptions-item>
        <a-descriptions-item label="司机信息" span="4">
          <p>司机姓名: {{ reportData.driver?.usernameWbxqy }}</p>
          <p>邮箱: {{ reportData.driver?.emailWbxqy }}</p>
          <p>电话号码: {{ reportData.driver?.phoneNumberWbxqy }}</p>
          <img :src="reportData.driver?.avatarUrlWbxqy" alt="司机头像" style="width: 50px; height: 50px;"/>
        </a-descriptions-item>
        <a-descriptions-item label="请求时间" span="12">{{ reportData.requestDateWbxqy }}</a-descriptions-item>
        <a-descriptions-item label="开始时间" span="6">{{ reportData.startTimeWbxqy }}</a-descriptions-item>
        <a-descriptions-item label="结束时间" span="6">{{ reportData.endTimeWbxqy }}</a-descriptions-item>
        <a-descriptions-item label="状态" span="12">
          <a-tag v-if="reportData.statusWbxqy === 'S'" color="blue">待审批</a-tag>
          <a-tag v-else-if="reportData.statusWbxqy === 'A'" color="green">已批准</a-tag>
          <a-tag v-else-if="reportData.statusWbxqy === 'R'" color="red">已拒绝</a-tag>
          <a-tag v-else-if="reportData.statusWbxqy === 'E'" color="gray">行程已结束</a-tag>
          <a-tag v-else-if="reportData.statusWbxqy === 'B'" color="gray">管理员已编写报表</a-tag>
        </a-descriptions-item>
        <a-descriptions-item label="行程列表" span="12">
          <ul>
            <li v-for="trip in reportData.tripList" :key="trip.tripIdWbxqy">
              <p>起点: {{ trip.startLocationWbxqy }} - 终点: {{ trip.endLocationWbxqy }}</p>
              <p>距离: {{ trip.distanceWbxqy }}公里</p>
              <p>状态:
                <a-tag v-if="trip.tripStatusWbxqy==='S'"
                       style="border-radius: 20px; background-color: #FFD700;color:black">
                  待出行
                </a-tag>
                <a-tag v-else-if="trip.tripStatusWbxqy==='I'"
                       style="border-radius: 20px; background-color: #32CD32;color:white">
                  进行中
                </a-tag>
                <a-tag v-else-if="trip.tripStatusWbxqy==='E'"
                       style="border-radius: 20px; background-color: #808080;color:white">
                  已完成
                </a-tag>
              </p>
            </li>
          </ul>
        </a-descriptions-item>
      </a-descriptions>
      <div style="height: 900px">
        <VueMarkdownEditor v-model="markdownContent" height="900"></VueMarkdownEditor>
      </div>
    </a-drawer>
  </a-card>
</template>

<script setup>
import {onMounted, reactive, ref} from 'vue';
import {
  addStatement,
  agreeCarRequest,
  getAllCarRequests,
  getFullCarRequest,
  listFreeCars,
  rejectCarRequest
} from '@/api/carRequestMG';
import {IconEdit, IconEye, IconRefresh, IconSearch} from '@arco-design/web-vue/es/icon';
import {listUsers} from "@/api/userMG";
import {listCars} from "@/api/carMG";
import {listFreeDrivers} from "@/api/driverMG";
import VueMarkdownEditor from "@kangc/v-md-editor";

const requests = ref([]);
const pagination = ref({
  current: 1,
  pageSize: 10,
  total: 0,
});
const columns = [
  {title: '申请ID', dataIndex: 'requestIdWbxqy'},
  {title: '申请人', dataIndex: 'userIdWbxqy', slotName: 'user'},
  {title: '车辆', dataIndex: 'carIdWbxqy', slotName: 'car'},
  {title: '司机', dataIndex: 'driverIdWbxqy', slotName: 'driver'},
  {title: '申请日期', dataIndex: 'requestDateWbxqy'},
  {title: '开始时间', dataIndex: 'startTimeWbxqy'},
  {title: '结束时间', dataIndex: 'endTimeWbxqy'},
  {title: '申请状态', dataIndex: 'statusWbxqy', slotName: 'status'},
  {
    title: '操作',
    dataIndex: 'operation',
    width: '150',
    align: 'center',
    slotName: 'operations',
    fixed: 'right'
  }
];
// 搜索相关操作
const searchFormRef = ref(null);
const search_form = ref({
  userId: '',
  carId: '',
  driverId: '',
  status: '',
});
// 获取查询列表数据
const users = ref()
const cars = ref()
const drivers = ref()
const fetchUsers = async () => {
  // 请求用户列表的方法
  users.value = await listUsers({'role': 'U'})
}

const fetchCars = async () => {
  // 请求车辆列表的方法
  cars.value = await listCars()
}
const fetchDrivers = async () => {
  // 请求司机列表的方法
  drivers.value = await listUsers({'role': 'S'})
}
const handleSearchSubmit = async ({values, errors}) => {
  await fetchCarRequests(values);
};

const fetchCarRequests = async (params) => {
  let res = await getAllCarRequests(params);
  requests.value = res.records;
  pagination.value.total = res.total;
  pagination.value.current = res.current;
};

const handlePaginationChange = async (page, pageSize) => {
  await fetchCarRequests({page, ...search_form.value});
};
// 审批相关操作
const showShenPiDrawer = ref(false)
const requestData = ref()

// 审批表单数据
// 审批表单数据
const approvalForm = reactive({
  driverIdWbxqy: null,
  carIdWbxqy: null,
  rejectResonWbxqy: '',
});
// 自定义验证规则，确保拒绝理由和其他字段不得同时填写
const validateDriverCarAndReason = (value, callback) => {
  if (approvalForm.rejectResonWbxqy && (approvalForm.driverIdWbxqy || approvalForm.carIdWbxqy)) {
    callback('拒绝理由和其他字段不得同时填写');
  } else if (!approvalForm.rejectResonWbxqy && (!approvalForm.driverIdWbxqy || !approvalForm.carIdWbxqy)) {
    callback('请填写分配司机和车辆或拒绝理由');
  } else {
    callback();
  }
}
// 表单验证规则
const shenPiRules = {
  driverIdWbxqy: [
    {validator: validateDriverCarAndReason, trigger: 'change'}
  ],
  carIdWbxqy: [
    {validator: validateDriverCarAndReason, trigger: 'change'}
  ],
  rejectResonWbxqy: [
    {validator: validateDriverCarAndReason, trigger: 'change'}
  ]
}
// 抽屉显示
const freeDrivers = ref()
const freeCars = ref()
const openShenPi = async (record) => {
  showShenPiDrawer.value = true;
  requestData.value = record
  freeDrivers.value = await listFreeDrivers(
      {'startTime': requestData.value.startTimeWbxqy, 'endTime': requestData.value.endTimeWbxqy})
  freeCars.value = await listFreeCars(
      {'startTime': requestData.value.startTimeWbxqy, 'endTime': requestData.value.endTimeWbxqy})
}
// 抽屉确认按钮事件
const approvalFormRef = ref();
const shenPiOk = () => {
  approvalFormRef.value.validate(async (valid) => {
    if (valid === undefined) {
      console.log("校验通过")
      if (approvalForm.rejectResonWbxqy) {
        // 提交拒绝审批表单逻辑
        console.log('拒绝审批:', approvalForm.rejectResonWbxqy);
        await rejectCarRequest(
            {
              "requestIdWbxqy": requestData.value.requestIdWbxqy,
              "rejectResonWbxqy": approvalForm.rejectResonWbxqy,
            },
        )
      } else {
        // 提交通过审批表单逻辑
        console.log('通过审批:', approvalForm);
        await agreeCarRequest(
            {
              "requestIdWbxqy": requestData.value.requestIdWbxqy,
              "carIdWbxqy": parseInt(approvalForm.carIdWbxqy),
              "driverIdWbxqy": parseInt(approvalForm.driverIdWbxqy)
            },
        )
      }
      await fetchCarRequests()
      showShenPiDrawer.value = false;
    }

  });
};

// 抽屉取消按钮事件
const shenPiCancel = () => {
  showShenPiDrawer.value = false;
};
let reportData = ref({})

// 报表相关
const showBaoBiaoDrawer = ref(false)
const markdownContent = ref("")
const currentRequestId = ref("")
const openBaoBiao = async (requestId) => {
  showBaoBiaoDrawer.value = true;
  currentRequestId.value = requestId;
  reportData.value = await getFullCarRequest({"carRequestId": requestId})

}
const openBaoBiaoShow = async (requestId) => {
  showBaoBiaoDrawer.value = true;
  currentRequestId.value = requestId;
  reportData.value = await getFullCarRequest({"carRequestId": requestId})
  markdownContent.value = reportData.value.statementWbxqy
}
const baoBiaoOk = async () => {
  // 处理同意并分配的逻辑
  console.log(currentRequestId.value)
  console.log(markdownContent.value)
  await addStatement({
    carRequestId: currentRequestId.value,
    statement: markdownContent.value
  })
  showBaoBiaoDrawer.value = false;
  markdownContent.value = ""
};

const baoBiaoCancel = () => {
  // 处理拒绝并说明的逻辑
  showBaoBiaoDrawer.value = false;
  markdownContent.value = ""
};
onMounted(() => {
  fetchCarRequests();
  fetchUsers();
  fetchCars();
  fetchDrivers();
});
</script>

<style scoped>
</style>
